package com.quancheng.component.requestformat.filter;

import com.quancheng.component.requestformat.filter.custom.ShapingRequestWrapper;
import com.quancheng.component.requestformat.filter.custom.ShapingResponseWrapper;
import com.quancheng.component.requestformat.util.JsonShapingUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zhouchaoqun
 * @email zhouchaoqun@quancheng-ec.com
 * @created 2018/2/2 下午2:30
 */
public class ParamShapingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = new ShapingRequestWrapper((HttpServletRequest) request);
        ShapingResponseWrapper responseWrapper = new ShapingResponseWrapper((HttpServletResponse) response);

        filterChain.doFilter(requestWrapper, responseWrapper);

        String respContent = responseWrapper.getTextContent();
        String shapedRespContent = JsonShapingUtil.toUnderScoreCase(respContent);
        response.getOutputStream().write(shapedRespContent.getBytes());
    }

    @Override
    public void destroy() {

    }
}
